package cn.miao.mq.consumers;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.miao.to.EmailTo;
import cn.miao.to.MessageTo;
import cn.miao.to.SMSTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static cn.miao.constants.MQConstant.*;

/**
 * @program: springcloud-hrm
 * @description: 定义课程消费者
 * @author: MiaoWei
 * @create: 2021-11-29 19:17
 **/
@Component
@Slf4j
public class CourseConsumer {

    @Value("${message.miao.emailTemplate}")
    private String emailTemplate;
    @Value("${message.miao.sms-template}")
    private String smsTemplate;
    @Value("${message.miao.message-template}")
    private String messageTemplate;


    /**
     * 邮件处理程序
     */
    @RabbitListener(queues = QUEUE_NAME_EMAIL, containerFactory = "rabbitListenerContainerFactory")
    public void emailHandler(@Payload EmailTo emailTo, Channel channel, Message message) throws IOException {
        for (String email : emailTo.getEmails()) {
            //1.准备要发送的消息
            String format = CharSequenceUtil.format(emailTemplate, email, emailTo.getId(), emailTo.getCourseName(), DateUtil.formatDate(emailTo.getOnlineTime()));
            //2.发送短信
            log.info(format);
            //消息确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
    /**
     * 短信处理程序
     */
    @RabbitListener(queues = QUEUE_NAME_SMS, containerFactory = "rabbitListenerContainerFactory")
    public void smsHandler(@Payload SMSTo smsTo, Channel channel, Message message) throws IOException {
        for (String sms : smsTo.getSmss()) {
            //1.准备要发送的消息
            String format = CharSequenceUtil.format(smsTemplate, sms, smsTo.getId(), smsTo.getCourseName(), DateUtil.formatDate(smsTo.getOnlineTime()));
            //2.发送短信
            log.info(format);
            //消息确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    /**
     * 站内信处理程序
     */
    @RabbitListener(queues = QUEUE_NAME_SYSTEM_MESSAGE, containerFactory = "rabbitListenerContainerFactory")
    public void messageHandler(@Payload MessageTo messageTo, Channel channel, Message message) throws IOException {
        for (String oneMessage : messageTo.getMessages()) {
            //1.准备要发送的消息
            String format = CharSequenceUtil.format(messageTemplate, oneMessage, messageTo.getId(), messageTo.getCourseName(), DateUtil.formatDate(messageTo.getOnlineTime()));
            //3.发送站内信
            log.info(format);
            //消息确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
